import { useEffect, useRef } from "react";
 
interface WebSocketService {
  send: (message: string) => void;
  addMessageListener: (listener: (message: string) => void) => void;
}
 
const useWebSocket = (url: string): WebSocketService => {
  const socketRef = useRef<WebSocket | null>(null);
  const messageListeners = useRef<((message: string) => void)[]>([]);
 
  useEffect(() => {
    const newSocket = new WebSocket(url);
    socketRef.current = newSocket;
 
    newSocket.addEventListener("open", () => {
      console.log("%c 【 Websocket 已建立连接! 】........  ", "color: green");
      newSocket.send("web 已连接!");
    });
 
    newSocket.addEventListener("message", (event) => {
      messageListeners.current.forEach((listener) => listener(event.data));
    });
 
    newSocket.addEventListener("close", () => {
      console.log("WebSocket连接已关闭");
    });
 
    return () => {
      newSocket.close();
    };
  }, [url]);
 
  const send = (message: string) => {
    if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
      socketRef.current.send(message);
    }
  };
 
  const addMessageListener = (listener: (message: string) => void) => {
    messageListeners.current.push(listener);
  };
 
  return { send, addMessageListener };
};
 
export default useWebSocket;